from . import profile_blue
from flask import render_template, g, redirect, request, jsonify, current_app

from ... import models, db, constants
from ...utils.commons import user_login_data
from ...utils.response_code import RET
from ...utils.image_storage import image_strorage


@profile_blue.route('/user_index')
@user_login_data
def user_index():
    if not g.user:
        return redirect('/')

    data = {
        "user_info": g.user.to_dict()
    }
    return render_template('news/user.html', data=data)


# 用户的基本信息
@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    try:
        if request.method == 'GET':
            data = {
                "user_info": g.user.to_dict()
            }
            return render_template('news/user_base_info.html', data=data)

        nick_name = request.json.get('nick_name')
        signature = request.json.get('signature')
        gender = request.json.get('gender')

        if not all([nick_name, signature, gender]):
            return jsonify(errno=RET.DATAERR, errmsg='参数错误')

        if gender not in ['MAN', 'WOMAN']:
            return jsonify(errno=RET.DATAERR, errmsg='性别参数有误')

        user_obj = models.User()
        user_obj.gender = gender
        user_obj.nick_name = nick_name
        user_obj.signature = signature
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.UNKOWNERR, errmsg='未知错误！')
    return jsonify(errno=RET.OK, errmsg='修改个人信息成功！')


# 上传用户头像的功能
@profile_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    if request.method == 'GET':
        data = {
            "user_info": g.user.to_dict()
        }
        return render_template('news/user_pic_info.html', data=data)
    avatar = request.files.get('avatar')

    if not avatar:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全！")

    try:
        # 将图片读取为二进制
        image_name = image_strorage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云异常！")
    if not image_name:
        return jsonify(errno=RET.NODATA, errmsg="图片上传失败！")
    g.user.avatar_url = image_name
    db.session.commit()
    data = {
        "avatar_url": constants.QINIU_DOMIN_PREFIX + image_name
    }
    return jsonify(errno=RET.OK, errmsg="上传成功", data=data)


# 修改密码的功能
@profile_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    try:
        if request.method == "GET":
            return render_template('news/user_pass_info.html')
        new_password = request.json.get('new_password')
        old_password = request.json.get('old_password')
        if not all([new_password, old_password]):
            return jsonify(errno=RET.DATAERR, errmsg='参数缺少')
        if not g.user.check_password(old_password):
            return jsonify(errno=RET.DATAERR, errmsg='密码错误')
        g.user.password = new_password
        db.session.commit()
    except Exception as e:
        return jsonify(errno=RET.UNKOWNERR, errmsg="未知错误！")
    return jsonify(errno=RET.OK, errmsg="修改密码成功！")


# 获取收藏新闻的列表
@profile_blue.route('/collection')
@user_login_data
def collection():
    page = request.args.get('p', '1')
    if g.user:
        paginate = g.user.collection_news.order_by(models.News.create_time.desc()).paginate(page=int(page), per_page=10,
                                                                                            count=False)
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    data = {
        'totalPage': totalPage,
        'currentPage': currentPage,
        'news_list': news_list
    }

    return render_template('news/user_collection.html', data=data)


@profile_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    if request.method == 'GET':
        try:
            categories = models.Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='获取分类失败！')

        category_list = []
        for category in categories:
            category_list.append(category.to_dict())
        data = {
            "categories": category_list
        }
        return render_template('news/user_news_release.html', data=data)
    # 3. 如果是POST,获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")

    # 4. 校验参数,为空校验
    if not all([title, category_id, digest, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 5. 上传图片,判断是否上传成功
    image_name = ''
    if index_image:
        try:
            # 读取图片为二进制数据,上传
            image_name = image_strorage(index_image.read())
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="七牛云异常")
        if not image_name:
            return jsonify(errno=RET.NODATA, errmsg="图片上传失败")
    else:
        # 6. 创建新闻对象,设置属性
        news = models.News()
        news.title = title
        news.source = g.user.nick_name
        news.digest = digest
        news.content = content
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
        news.category_id = category_id
        news.user_id = g.user.id
        news.status = 1  # 表示审核中

        # 7. 保存到数据
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="新闻发布失败")

    # 8. 返回响应
    return jsonify(errno=RET.OK, errmsg="发布成功")


# 用户新闻列表
@profile_blue.route('/news_list')
@user_login_data
def news_list():
    page = request.args.get('p', '1')
    if not g.user:
        return jsonify(errno=RET.NODATA, errmsg='用户为登录')

    paginate = models.News.query.filter(models.News.user_id == g.user.id).order_by(
        models.News.create_time.desc()).paginate(page=int(page), per_page=3,
                                                 count=False)
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    news_list = []
    for news in items:
        news_list.append(news.to_review_dict())

    data = {
        'totalPage': totalPage,
        'currentPage': currentPage,
        'news_list': news_list
    }

    return render_template('news/user_news_list.html', data=data)


# 获取我的关注
@profile_blue.route('/user_follow')
@user_login_data
def user_follow():
    # 1. 获取参数,p
    page = request.args.get("p", "1")

    # 2. 参数类型转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 3. 分页查询用户关注的作者
    try:
        paginate = g.user.followed.paginate(page=page, per_page=2, count=False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取作者失败")

    # 4. 获取分页对象属性,总页数,当前页,当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 5. 将对象列表,转成字典列表
    author_list = []
    for author in items:
        author_list.append(author.to_dict())

    # 6. 拼接数据,渲染页面
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "author_list": author_list
    }
    return render_template("news/user_follow.html", data=data)
